//
//  DesignatedDrivingServiceViewController.m
//  CPICMobileServiceApp
//
//  Created by lizhiwei on 13-2-17.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "DesignatedDrivingServiceViewController.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "RCAlertViewUtil.h"
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"

#define CallOutBtnWidth 355
#define CallOutBtnHeight 74

@interface DesignatedDrivingServiceViewController ()

@end

@implementation DesignatedDrivingServiceViewController
//@synthesize Latitude;
//@synthesize Longitude;
@synthesize CurrentLocation;
@synthesize CurrentAddress;
@synthesize progress;
@synthesize currentState;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"代驾服务";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImageView * BgImage = [[UIImageView alloc]init];
    BgImage.image = [UIImage imageNamed:@"代驾服务"];
    BgImage.frame = CGRectMake(0, 0, BgImage.image.size.width/2, BgImage.image.size.height/2);
    [self.view addSubview:BgImage];
    [BgImage release];
    
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"代驾服务");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"代驾服务");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"代驾服务");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }

	//网络状态监测
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name: kReachabilityChangedNotification
                                               object: nil];
    hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
    [hostReach startNotifier];
    
}

// 通知网络状态
- (void)reachabilityChanged:(NSNotification *)note {
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    currentState = [curReach currentReachabilityStatus];
    
    if (currentState == NotReachable)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"没有网络连接"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else
    {
        //添加“呼叫95500”按钮
        UIButton * CallOutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn.frame = CGRectMake((self.view.frame.size.width-CallOutBtnWidth/2)/2, 220+44, CallOutBtnWidth/2, CallOutBtnHeight/2);
        [CallOutBtn setTitle:@"呼叫代驾服务电话" forState:UIControlStateNormal];
        [CallOutBtn setBackgroundImage:[UIImage imageNamed:@"callBg355X74.png"] forState:UIControlStateNormal];
        [CallOutBtn addTarget:self action:@selector(ClickCallOut1Btn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn];
        
        [self setTelephoneQryRequest];
        
        //添加当前位置
        CurrentLocation = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-300)/2, 324, 300, 30)];
        CurrentLocation.font = [UIFont systemFontOfSize:13.0];
        CurrentLocation.text=@"当前位置:";
        [self.view addSubview:CurrentLocation];
        
        //添加当前地址
        CurrentAddress = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-300)/2, 356, 300, 30)];
        CurrentAddress.font = [UIFont systemFontOfSize:13.0];
        CurrentAddress.text = @"当前地址：";
        [self.view addSubview:CurrentAddress];
        
        //初始化maSearch
        maSearch=[[MASearch alloc]init];
        maSearch.delegate=self;
        
        //初始化poiArray
        poiArray=[[NSMutableArray alloc]init];
        
        mamapView=[[MAMapView alloc]initWithFrame:CGRectMake(0,0, 320,416)];
        mamapView.delegate=self;
        mamapView.showsUserLocation=YES;
        
        [self setEvaluationRequest];

    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [poiArray removeAllObjects];
    [super viewWillAppear:animated];
}

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
{
    Longitude = [NSString stringWithFormat:@"%3.6f",userLocation.location.coordinate.longitude];
    Latitude = [NSString stringWithFormat:@"%3.6f",userLocation.location.coordinate.latitude];
    NSString * CurrentLocatinStr = [NSString stringWithFormat:@"当前位置：%@/%@",Longitude,Latitude];
    CurrentLocation.text = CurrentLocatinStr;
    
    MAReverseGeocodingSearchOption *searchOption=[[MAReverseGeocodingSearchOption alloc] init];
    searchOption.multiPoint=@"0";
    searchOption.config=@"SPAS";
    searchOption.x=Longitude;
    searchOption.y=Latitude;
    searchOption.xCoors=Longitude;
    searchOption.yCoors=Latitude;
    [maSearch reverseGeocodingSearchWithOption:searchOption];
    [searchOption release];
    
    [mamapView setShowsUserLocation:NO];
}

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error NS_AVAILABLE(NA, 4_0){
    NSLog(@"+++++++++++++failLocation");
    
}

-(NSString*)keyForSearch
{
    return @"c14816a5330213770ea772273a41bc24";
}

-(void)search:(id)searchOption Error:(NSString*)errCode
{
    NSLog(@"ERROR:%@",errCode);
    if([errCode isEqualToString:@"040001"])
    {
        [self justShowMessage:@"查询服务连接异常" title:@"提示"];
        return;
    }
}

//@property(nonatomic,retain) NSArray* roads;//道路信息 MARoad对象队列
//@property(nonatomic,retain) NSArray* pois;//poi信息 MAPOI对象队列
//@property(nonatomic,retain) NSArray* crosses;//道路交叉口信息

-(void)reverseGeocodingSearch:(MAReverseGeocodingSearchOption*)geoCodingSearchOption Result:(MAReverseGeocodingSearchResult*)result
{
    poiArray=(NSMutableArray *)result.resultArray;
    for(MAReverseGeocodingInfo *info in result.resultArray)
    {
        MARoad* revRoad = [info.roads objectAtIndex:0];
        NSString * CurrentAddressStr = [NSString stringWithFormat:@"当前地址：%@%@%@%@",info.province.name,info.city.name,info.district.name,revRoad.name];
        CurrentAddress.text = CurrentAddressStr;
    }
}

-(void) ClickCallOutBtn
{
    if ([Flag isEqualToString:@"0"]) 
    {
        [self IFServiceEvaluation];
        Flag = @"1";
    }
    else 
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void) ClickCallOut1Btn
{
    //呼叫95500
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:Telephone];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    [self.view addSubview:callWebview];
    Flag = @"0";
}

-(void)setEvaluationRequest
{
    NSLog(@"==================");
    NSString *serviceid =@"40505";
    NSString *servicename =@"代驾服务";
    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
    [ifserviceevaluation setIfServiceEvaluationRequest];
    [ifserviceevaluation setHidden:YES];
    [self.view addSubview:ifserviceevaluation];
    [ifserviceevaluation release];
}
-(void) IFServiceEvaluation
{
    NSString *serviceid =@"40505";
    NSString *servicename =@"代驾服务";
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if ([myDefaults stringForKey:serviceid]) {
        NSString *strEvaluate=[myDefaults stringForKey:serviceid];
        if ([strEvaluate isEqualToString:@"1"]) {
            AddServiceEvaluationViewController *serviceevluation = [[AddServiceEvaluationViewController alloc]initView:serviceid withserviceName:servicename];
            [[AppDelegate app].unc pushViewController:serviceevluation animated:YES];
            [serviceevluation release];
        }
        else
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}


-(void)setTelephoneQryRequest//向太保移动平台发送电话号码类查询请求报文
{
    /*---------------------------
     服务类型定义如下所示:
     自助报案电话，ServerType=PH_1001、
     联系客服电话，ServerType=PH_1002、
     电话投保电话:ServerType=PH_1003、
     救援服务电话，ServerType=PH_1004、
     代驾服务电话，ServerType=PH_1005
     -----------------------------*/
    
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    
    NSString * useraccount = [dictUserInfo valueForKey:@"UserAccount"];
//    NSString *strRequestCode=@"RequestCode=40501";
    NSString *strRequestData=[NSString stringWithFormat:@"{\"ServerType\":\"PH_1005\",\"UserAccount\":\"%@\"}",useraccount];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestData];
//    NSLog(@"++++++++++++++%@",strUrl);
//    strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    
//    NSURL *myurl = [NSURL URLWithString:strUrl];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"URL:%@",myurl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"40501" forKey:@"RequestCode"];
    [request setPostValue:strRequestData forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"加载中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSMutableDictionary *jsonoSubObj = [dictResponse objectForKey:@"head"];
    NSString * ss = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"success"]];
    if ([ss isEqualToString:@"1"])
    {
        NSString *servicePhone = [[NSString alloc] initWithFormat:@"%@",[dictResponse objectForKey:@"servicePhone"]];
        Telephone = [[NSString alloc] initWithFormat:@"tel:%@",servicePhone];
        NSLog(@"-----------%@",Telephone);
    }
    else
    {
        [self justShowMessage:@"获取号码失败！" title:@"提示"];
    }
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    /*[Latitude release];
     [Longitude release];
     [CurrentAddress release];
     [CurrentLocation release];
     [mamapView release];
     mamapView = nil;
     [MASearch release];*/
    [progress release];
}

-(void)dealloc
{
    [mamapView setShowsUserLocation:NO];
    mamapView.delegate=nil;
    maSearch.delegate=nil;
    [mamapView release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
